package com.alibaba.cloud.ai.example.prompt.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

@RestController
public class ImageModelController {

    private final ImageModel imageModel;

    private final String DEFAULT_PROMPT = "为人工智能生成一张有点像{starName}的照片！";

    public ImageModelController(ImageModel imageModel) {
        this.imageModel = imageModel;
    }


    @GetMapping("/image")
    public void image(HttpServletResponse response) {

        ImageResponse imageResponse = imageModel.call(new ImagePrompt(DEFAULT_PROMPT.format("热依扎")));
        String imageUrl = imageResponse.getResult().getOutput().getUrl();

        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream in = url.openStream();

            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(in.readAllBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("/imageWithOptions")
    public String imageWithOptions(@RequestParam(value = "starName", defaultValue = "刘亦菲") String input) {
        ImageOptions options = ImageOptionsBuilder.builder() //.model("dall-e-3")
                .width(1024).height(1024)
                .build();

        var input1 = DEFAULT_PROMPT.format(input);
        ImagePrompt imagePrompt = new ImagePrompt(input1, options);
        ImageResponse response = imageModel.call(imagePrompt);
        String imageUrl = response.getResult().getOutput().getUrl();

        return "redirect:" + imageUrl;
    }
}
